package com.apes.fn.server.servicePlan.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.crm.car.service.CarTypeLimitService;
import com.apes.fn.crm.customer.FnApiService;
import com.apes.fn.server.servicePlan.model.GetPriceLogger;
import com.apes.fn.server.servicePlan.repository.GetPriceLoggerRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.util.Arith;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.car.model.CarServiceLevel;
import com.apes.scm.masterdata.car.service.CarConfigurationService;
import com.apes.scm.masterdata.car.service.CarServiceLevelService;
import com.apes.scm.masterdata.finance.model.CooperateType;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.service.StoreService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import com.apes.scm.masterdata.product.model.Classify;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import org.bson.Document;
import org.junit.rules.Stopwatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * @program: apes-server
 * @description
 * @author: czs
 * @create: 2022-03-24 14:54
 **/
@Service("priceConditionService")
public class PriceConditionService extends DomainService {
    @Autowired
    private PiManager piManager;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private ProductUomRepository productUomRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private GetPriceLoggerRepository getPriceLoggerRepository;

    @Value("${apes.switched:false}")
    private Boolean switched;

    /**
     * 查找价格总入口
     * @param condi
     * @return
     */
    public Object executePriceMethod(JSONObject condi){
        Object obj = null;
        try{
            obj = this.invoke("condition.execConditionStrategy", condi);
        }catch (Exception e){
            writeDB(condi,e.getMessage(),new JSONObject());
            throw new RuntimeException(e.getMessage());
        }
        String loggerId = writePriceLogger(condi, obj);
        com.apestech.framework.json.JSONObject jsonObject = (com.apestech.framework.json.JSONObject) obj;
        jsonObject.put("priceSource",loggerId);
        return jsonObject;
    }

    /**
     * 写价格日志
     * @param condi 条件
     * @param obj 返回值
     */
    private String writePriceLogger(JSONObject condi, Object obj) {
        try {
            GetPriceLogger getPriceLogger = new GetPriceLogger();

            String conditionStrategyId = condi.getString("conditionStrategyId");
            getPriceLogger.setConditionStrategyId(conditionStrategyId);
            getPriceLogger.setProductId(condi.getString("PRODUCT_ID"));
            getPriceLogger.setDeptId(condi.getString("DEPT_ID"));
            getPriceLogger.setSysDate(condi.getDate("SYS_RQ"));
            getPriceLogger.setCarLicense(condi.getString("CAR_LICENSE"));
            getPriceLogger.setConditionParam(condi.toJSONString());
            com.apestech.framework.json.JSONObject jsonObject = (com.apestech.framework.json.JSONObject) obj;
            getPriceLogger.setConditionResult(jsonObject.toString());
            getPriceLoggerRepository.saveAndFlush(getPriceLogger);
            return getPriceLogger.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void delPriceLogger(String loggerId){
        try {
            GetPriceLogger getPriceLogger = getPriceLoggerRepository.findOne(loggerId);
            if (getPriceLogger==null)return;
            getPriceLogger.setValid(false);
            getPriceLoggerRepository.saveAndFlush(getPriceLogger);
//            getPriceLoggerRepository.delete(loggerId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Object executePriceMethod(Map condi){
        return executePriceMethod(new JSONObject(condi));
    }

    /**
     * 写MongoDB日志获取错误信息
     */
    private void writeDB(JSONObject condition,String Msg,Object result){
        if (false)return;
        Document document = new Document();
        document.put("priceType", condition.getString("conditionStrategyId"));
        document.put("param", condition);
        document.put("carLicense", condition.getString("CAR_LICENSE"));
        document.put("date",new Date());
        document.put("result",result);
        document.put("ExceptionMsg",Msg);
        mongoTemplate.getCollection("ServicePriceException").insertOne(document);
    }

    /**
     * 根据标记取xs55价格或者xj51
     */
    public JSONObject getXS55OrXJ51(JSONObject result){
        Boolean xjbj = result.getBoolean("XJBJ")==null?false:result.getBoolean("XJBJ");
        if (!xjbj){//判断是否是采购价格文件价格
            if(result.getString("P001") == null){
                return new JSONObject(MapUtil.mapper(
                        "S950",0,//公司间定价
                        "Z002",0, //原售价
                        "S901",0, //销售单价
                        "F008",0, //管理费率
                        "P005",0,  //最低限价
                        "S001",0,
                        "Z002",0,
                        "P008",0,
                        "P006",0,
                        "P001",0 //采购基准价
                ));
            }
            return result;
        }else {
            if(!result.containsKey("S901") || result.getDouble("S901") <= 0){
                return new JSONObject(MapUtil.mapper(
                        "S950",0,//公司间定价
                        "Z002",0, //原售价
                        "S901",0, //销售单价
                        "F008",0, //管理费率
                        "P005",0,  //最低限价
                        "S001",0,
                        "Z002",0,
                        "P008",0,
                        "P006",0,
                        "P001",0, //采购基准价
                        "F001",0 //配件加价率
                ));
            }
            return new JSONObject(
                    MapUtil.mapper(
                            "Z002",result.getDouble("Z002"),
                            "S901",result.getDouble("S901"),
                            "F008",result.containsKey("F008")?result.getDouble("F008"):0,
                            "P005",result.containsKey("P005")?result.getDouble("P005"):0,  //最低限价
                            "S801",result.containsKey("S801")?result.getDouble("S801"):0,
                            "S802",result.containsKey("S802")?result.getDouble("S802"):0,
                            "S803",result.containsKey("S803")?result.getDouble("S803"):0,
                            "Z002",result.containsKey("Z002")?result.getDouble("Z002"):0,
                            "P006",result.containsKey("P006")?result.getDouble("P006"):0,
                            "P008",result.containsKey("P008")?result.getDouble("P008"):0,
                            // "S950",result.containsKey("CGDJ")?Arith.div(result.getDouble("CGDJ"),1-result.getDoubleValue("F001"),2):0,
                            // "P001",result.containsKey("CGDJ")?Arith.div(result.getDouble("CGDJ"),1-result.getDoubleValue("F001"),2):0,
                            "S950",result.containsKey("S950")?result.getDouble("S950"):0,
                            "P001",result.containsKey("S950")?result.getDouble("S950"):0,
                            "expectedArrivalTime",result.getDouble("YJDHSC"),
                            "inquiryGooodsState",result.getString("HYZT"),
                            "oldInquiryNumber",result.getString("XJDH")
                    )
            );
        }
    }


    public Map getNewXS55Map(Map result){
        result.put("conditionStrategyId", "XS55");
        result.put("SYS_RQ", new Date());
        result.put("NOT_SPXJD_CREATE", "1");
        result.put("SYS_NO_CHECK", "SUPPLIER_ID");

        result.put("CAR_LICENSE", result.get("CPHM"));
        result.put("SAL_COMPANY_ID", result.get("GSID"));
        result.put("PUR_COMPANY_ID", result.get("SYGSID"));
        result.put("SUPPLIER_ID", result.get("GYSID"));
        result.put("PRODUCT_ID", result.get("SPID"));
        result.put("COMPANY_ID", result.get("GSID"));
        result.put("DEPT_ID", result.get("MDID"));
        result.put("USABLE_QTY", result.get("KYS"));
        result.put("ACCESS_PROVIDER_ID", result.get("JRS"));

        result.put("BRAND_ID", result.get("PPID"));
        result.put("CLASSIFY_ID", result.get("PLID"));
        result.put("OPERATION", result.get("NYYMS"));

        result.put("QUALITY", result.get("PZID"));
        result.put("CUSTOMER_ID", result.get("FNKHID"));

        result.put("CAR_SERVICE_LEVEL_ID", result.get("CLFWDJID"));
        result.put("VIP_IDENTITY_ID", result.get("VIPSFID"));
        result.put("CJHM", result.get("CJHM"));
        result.put("BUSINESS_CIRCLE_ID", result.get("SQID"));

        result.put("P001", result.get("P001")==null? 0:result.get("P001"));
        result.put("P004", result.get("P004")==null? 0:result.get("P004"));
        result.put("P005", result.get("P005")==null? 0:result.get("P005"));



        return result;
    }


    public Map getGS51Map(Dept belongDept, Dept saleDept, Product product, PartyRole platform, ProductUom uom, JSONObject fnCustomer, JSONObject carJson){
        fnCustomer.putAll(carJson);
        return MapUtil.mapper(
                "SPID", product.getId(),
                "PZID", product.getBrand().getQuality() == null ? null : product.getBrand().getQuality().getCode(),
                "PLID", product.getClassify().getId(),
                "GSID", belongDept.getCompany().getId(),
                "YYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getCode(),
                "NYYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getId(),
                "KHID", SpringManager.getBean(PartyRoleService.class)
                        .findByPartyAndRole(saleDept.getCompany().getParty().getId(), "Customer").getId(),
                "CGZZID", platform.getId(),
                "JLDW", uom.getName(),
                "JLDWID", uom.getId(),
                "JRS", fnCustomer.getString("vendorCode"),
                "SYGSID", platform.getId(),
                "JCGSID", saleDept.getCompany().getId(),
                "CLFWDJID", ((CarServiceLevel) (SpringManager.getBean(CarServiceLevelService.class).findByCarConfigurationId(carJson.getString("jekunModelCode")))).getId()
        );
    }

    public Map getXS51Map(Dept belongDept, Product product, CooperateType cooperateType, JSONObject carJson, JSONObject fnCustomer,
                          PartyRole platform, ProductUom uom, Double planKys){
        fnCustomer.putAll(carJson);
        return MapUtil.mapper(
                "MDID", belongDept.getOrigin(),
                "PLID", product.getClassify().getId(),
                "SPID", product.getId(),
                "PZID", product.getBrand().getQuality() == null ? null : product.getBrand().getQuality().getCode(),
                "HZLXID", cooperateType == null ? null : cooperateType.getId(),
                "PPID", product.getBrand().getId(),   //品牌找品质
                "XSZZID", belongDept.getCompany().getId(),
                "GSID", belongDept.getCompany().getId(),
                "CLFWDJID", ((CarServiceLevel) (SpringManager.getBean(CarServiceLevelService.class).findByCarConfigurationId(fnCustomer.getString("jekunModelCode")))).getId(),
                "FNKHID", fnCustomer.getJSONObject("unitClient") == null ? null : fnCustomer.getJSONObject("unitClient").getString("clientCode"),
                //"MDLXID", belongDept.getDeptType().getId(),
                "FNVIPJBID", fnCustomer.getString("level"),
                "FNVIPSFID", fnCustomer.getJSONObject("userRole") == null ? null : fnCustomer.getJSONObject("userRole").getString("id"),
                "CGZZID", platform.getId(),
                "JLDW", uom.getName(),
                "YYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getCode(),
                "NYYMS", belongDept.getCompany().getParty().getCorporate().getOperation().getId(),
                "SYGSID", platform.getId(),
                "SQID", SpringManager.getBean(StoreService.class).findBusinessCircleByDept(belongDept).getId(),
                "XYGSID", belongDept.getCompany().getId(),
                "JRS",fnCustomer.getString("vendorCode"),
                "CPHM",fnCustomer.getString("carLicense"),
                "SJHM",fnCustomer.getString("mobile"),
                "JLDWID", uom.getId(),
                "XSMD",belongDept.getId(),
                "CJHM",fnCustomer.getString("vin"),
                "KYS",planKys
        );
    }


    /**
     * 获取XS51map
     *
     * @param map
     * @return
     */
    public Map getXS51Map(Map map) {
        map.put("DJGCID", "XS51");
        map.put("MDID", map.get("MDID") == null ? null : map.get("MDID"));
        map.put("PLID", map.get("PLID") == null ? null : map.get("PLID"));
        map.put("SPID", map.get("SPID") == null ? null : map.get("SPID"));
        map.put("HZLXID", map.get("HZLXID") == null ? null : map.get("HZLXID"));
        map.put("PZID", map.get("PZID") == null ? null : map.get("PZID"));
        map.put("XSZZID", map.get("XSZZID") == null ? null : map.get("XSZZID"));
        map.put("GSID", map.get("GSID") == null ? null : map.get("GSID"));
        map.put("GYSID", map.get("GYSID") == null ? null : map.get("GYSID"));
        map.put("CLFWDJID", map.get("CLFWDJID") == null ? null : map.get("CLFWDJID"));
        map.put("MDLXID", map.get("MDLXID") == null ? null : map.get("MDLXID"));
        map.put("FNKHID", map.get("FNKHID") == null ? null : map.get("FNKHID"));
        map.put("FNVIPJBID", map.get("FNVIPJBID") == null ? null : map.get("FNVIPJBID"));
        map.put("FNVIPSFID", map.get("FNVIPSFID") == null ? null : map.get("FNVIPSFID"));
        map.put("CGZZID", map.get("CGZZID") == null ? null : map.get("CGZZID"));
        map.put("JLDW", map.get("JLDW") == null ? null : map.get("JLDW"));
        map.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
        map.put("XYGSID", map.get("XYGSID") == null ? null : map.get("XYGSID"));
        map.put("YYMS", map.get("YYMS") == null ? null : map.get("YYMS"));
        map.put("SQID", map.get("SQID") == null ? null : map.get("SQID"));
        map.put("USABLE_QTY", map.get("KYS") == null ? null : map.get("KYS"));
        map.put("CJHM", map.get("CJHM") == null ? null : map.get("CJHM"));
        map.put("NOT_SPXJD_CREATE", 1);
        return map;
    }

    /**
     * 获取新系统XS51map
     *
     * @param map
     * @return
     */
    public JSONObject getNewXS51Map(Map map) {
        JSONObject result = new JSONObject();
        result.put("conditionStrategyId", "XS51");
        result.put("SYS_RQ", new Date());
        result.put("SYS_NO_CHECK", "SUPPLIER_ID");

        result.put("PUR_COMPANY_ID", map.get("CGZZID") == null ? null : map.get("CGZZID"));
        result.put("PRODUCT_ID", map.get("SPID") == null ? null : map.get("SPID"));
        result.put("PRODUCT_UOM_ID", map.get("JLDWID") == null ? null : map.get("JLDWID"));
        result.put("BRAND_ID", map.get("PPID") == null ? null : map.get("PPID"));
        result.put("QUALITY", map.get("PZID") == null ? null : map.get("PZID"));
        result.put("CLASSIFY_ID", map.get("PLID") == null ? null : map.get("PLID"));

        result.put("SAL_COMPANY_ID", map.get("XYGSID") == null ? null : map.get("XYGSID"));
        result.put("ACCESS_PROVIDER_ID", map.get("JRS") == null ? null : map.get("JRS"));
        result.put("DEPT_ID", map.get("XSMD") == null ? null : map.get("XSMD"));
        result.put("BUSINESS_CIRCLE_ID", map.get("SQID") == null ? null : map.get("SQID"));

        result.put("PHONE_NUMBER", map.get("SJHM") == null ? null : map.get("SJHM"));
        result.put("VIP_IDENTITY_ID", map.get("FNVIPSFID") == null ? null : map.get("FNVIPSFID"));
        result.put("VIP_LEVEL_ID", map.get("FNVIPJBID") == null ? null : map.get("FNVIPJBID"));
        result.put("CAR_SERVICE_LEVEL_ID", map.get("CLFWDJID") == null ? null : map.get("CLFWDJID"));
        result.put("CAR_LICENSE", map.get("CPHM") == null ? null : map.get("CPHM"));
        result.put("COOPERATION_TYPE", map.get("HZLXID") == null ? null : map.get("HZLXID"));

        result.put("CUSTOMER_ID", map.get("FNKHID") == null ? null : map.get("FNKHID"));
        result.put("COMPANY_ID", map.get("GSID") == null ? null : map.get("GSID"));
        result.put("SUPPLIER_ID", map.get("GYSID") == null ? null : map.get("GYSID"));
        result.put("OPERATION", map.get("NYYMS") == null ? null : map.get("NYYMS"));
        result.put("uniqueIdentify", map.get("uniqueIdentify") == null ? null : map.get("uniqueIdentify"));
        result.put("PRODUCT_NAME", map.get("SPMC") == null ? null : map.get("SPMC"));
        result.put("USABLE_QTY", map.get("KYS") == null ? null : map.get("KYS"));
        result.put("CJHM", map.get("CJHM") == null ? null : map.get("CJHM"));

//        result.put("XSZZID", map.get("XSZZID") == null ? null : map.get("XSZZID"));
//        result.put("MDLXID", map.get("MDLXID") == null ? null : map.get("MDLXID"));
//        result.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
        return result;
    }


    /**
     * 根据标记取xs51价格或者xj51
     * appFalg 电商价格标记
     */
    public JSONObject getXS51OrXJ51(JSONObject result,boolean appFalg){
        Boolean xjbj = result.getBoolean("XJBJ")==null?false:result.getBoolean("XJBJ");
        double z002 = result.getDoubleValue("Z002");
        if (!xjbj){
            //xs51
            if (result.getString("P001") == null) {
                delPriceLogger(result.getString("priceSource"));
                return new JSONObject(MapUtil.mapper(
                        "primaryPriceUnit", 0,
                        "priceUnit", 0,
                        "pftPriceUnit", 0,
                        "managementFeeRate", 0,
                        "floorPrice", 0,  //最低限价
                        "clerkPriceLimit", 0,
                        "shopOwnerPriceLimit", 0,
                        "csoPriceLimit", 0,
                        "basePrice", 0,
                        "discountRate", 0,
                        "priceCostUnitInTax", 0,
                        "priceCostUnitExTax", 0,
                        "platformPriceCosInTax", 0,
                        "referTax", 0,
                        "supplyChainManagement", 0,     //供应链管理费用
                        "supplyRate", 0
                ));
            }

            //
            return new JSONObject(MapUtil.mapper(
                    "primaryPriceUnit", z002,
                    "priceUnit", result.getDoubleValue("S901"),
                    "pftPriceUnit", result.getDoubleValue("S901"),
                    "managementFeeRate", result.getDoubleValue("F008"),
                    "floorPrice", result.getDoubleValue("P005"),  //最低限价
                    "clerkPriceLimit", result.getDoubleValue("S801"),
                    "shopOwnerPriceLimit", result.getDoubleValue("S802"),
                    "csoPriceLimit", result.getDoubleValue("S803"),
                    "basePrice", result.getDoubleValue("P004"),
                    "discountRate", result.getDoubleValue("S901") / (z002==0?result.getDoubleValue("S901"):z002),
                    "priceCostUnitInTax", result.getDoubleValue("S950"),
                    "priceCostUnitExTax", result.getDoubleValue("S950"),
                    "platformPriceCosInTax", result.getDoubleValue("S904"),
                    "referTax", result.getDoubleValue("P008"),
                    "supplyChainManagement", result.getDoubleValue("S950"),     //供应链管理费用
                    "vipDiscountPrice", result.getDoubleValue("S206"),     //会员折扣价
                    "vipDiscountRate", result.getDoubleValue("S201"),     //会员折扣率
                    "priceSource", result.getString("priceSource"),     //价格来源日志
                    "supplyRate", result.getDoubleValue("T001")
            ));
        }else {
            if (!result.containsKey("S901") || result.getDouble("S901") <= 0) {
                delPriceLogger(result.getString("priceSource"));
                return new JSONObject(MapUtil.mapper(
                        "primaryPriceUnit", 0,
                        "priceUnit", 0,
                        "pftPriceUnit", 0,
                        "managementFeeRate", 0,
                        "floorPrice", 0,  //最低限价
                        "clerkPriceLimit", 0,
                        "shopOwnerPriceLimit", 0,
                        "csoPriceLimit", 0,
                        "basePrice", 0,
                        "discountRate", 0,
                        "priceCostUnitInTax", 0,
                        "priceCostUnitExTax", 0,
                        "platformPriceCosInTax", 0,
                        "supplyChainManagement", 0,     //供应链管理费用
                        "supplyRate", 0,
                        "referTax", 0
                ));
            }
            return new JSONObject(
                    MapUtil.mapper(
                            "primaryPriceUnit", z002,
                            "priceUnit", result.getDoubleValue("S901"),
                            "pftPriceUnit", result.getDoubleValue("S901"),
                            "managementFeeRate", result.getDoubleValue("F008"),
                            "floorPrice", result.getDoubleValue("P005"),  //最低限价
                            "clerkPriceLimit", result.getDoubleValue("S801"),
                            "shopOwnerPriceLimit", result.getDoubleValue("S802"),
                            "csoPriceLimit", result.getDoubleValue("S803"),
                            "basePrice", z002,
                            "discountRate", z002 == 0 ? 0 : result.getDouble("S901") / result.getDouble("Z002"),
                            "priceCostUnitInTax", result.getDoubleValue("S950"), // 配件成本加价。
                            "priceCostUnitExTax", result.getDoubleValue("S950"),
                            "platformPriceCosInTax", result.getDoubleValue("S950"),
                            "expectedArrivalTime", result.getDoubleValue("YJDHSC"),
                            "inquiryPriceUnit", result.getDoubleValue("S901"),
                            "inquiryPriceLimit", result.getDoubleValue("P005"),
                            "inquiryGooodsState", result.getDoubleValue("HYZT"),
                            "purchaseRemarks", result.getString("CGBZ"),
                            "supplierRemarks", result.getString("GYSBZ"),
                            "oldInquiryNumber", result.getString("XJDH"),
                            "supplier",result.getString("SUPPLIER_ID"),
                            "supplyChainManagement", result.getDoubleValue("S950"),     //供应链管理费用
                            "supplyRate", result.getDoubleValue("T001"),
                            "uniqueValue", result.getString("WYZ"),
                            "vipDiscountPrice", result.getDoubleValue("S206"),     //会员折扣价
                            "vipDiscountRate", result.getDoubleValue("S201"),     //会员折扣率
                            "priceSource", result.getString("priceSource"),
                            "referTax", result.getDoubleValue("P008") == 0 ? (1 + result.getDouble("P006")) * result.getDoubleValue("S950") : result.getDoubleValue("P008")

                    )
            );
        }
    }

    /**
     * 获取XJ51map
     *
     * @param map
     * @return
     */
    public Map getXJ51Map(Map map) {
        map.put("DJGCID", "XJ51");
        //公司
        map.put("GSID", map.get("GSID") == null ? null : map.get("GSID"));
        map.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
        map.put("XYGSID", map.get("XYGSID") == null ? null : map.get("XYGSID"));
        map.put("YYMS", map.get("YYMS") == null ? null : map.get("YYMS"));
        //商品
        map.put("SPID", map.get("SPID") == null ? null : map.get("SPID"));
        map.put("PLID", map.get("PLID") == null ? null : map.get("PLID"));
        map.put("JLDW", map.get("JLDW") == null ? null : map.get("JLDW"));
        //价格
        map.put("XSDJ", map.get("XSDJ") == null ? null : map.get("XSDJ"));
        map.put("XSXJ", map.get("XSXJ") == null ? null : map.get("XSXJ"));
        map.put("P001", map.get("P001") == null ? null : map.get("P001"));
        //会员
        map.put("FNVIPJBID", map.get("FNVIPJBID") == null ? null : map.get("FNVIPJBID"));
        map.put("FNVIPSFID", map.get("FNVIPSFID") == null ? null : map.get("FNVIPSFID"));
        map.put("FNKHID", map.get("FNKHID") == null ? null : map.get("FNKHID"));
        return map;
    }

    /**
     * 获取新系统XJ51map
     *
     * @param map
     * @return
     */
    public JSONObject getNewXJ51map(Map map) {
        JSONObject result = new JSONObject();
        result.put("conditionStrategyId", "XJ51");
        result.put("SYS_RQ", new Date());
        result.put("NOT_SPXJD_CREATE", "0");

        result.put("CLASSIFY_ID", map.get("PLID"));
        result.put("CUSTOMER_ID", map.get("FNKHID"));
        result.put("VIP_IDENTITY_ID", map.get("FNVIPSFID"));
        result.put("VIP_LEVEL_ID", map.get("FNVIPJBID"));

        result.put("ACCESS_PROVIDER_ID", map.get("JRS"));
        result.put("COMPANY_ID", map.get("GSID"));
        result.put("BRAND_ID", map.get("PPID"));
        result.put("OPERATION", map.get("NYYMS"));
        result.put("PRODUCT_ID", map.get("SPID"));
        result.put("SUPPLIER_ID", map.get("GYSID"));
        result.put("SAL_COMPANY_ID", map.get("XYGSID"));
        result.put("PUR_COMPANY_ID", map.get("SYGSID"));

        result.put("P001", map.get("P001") == null ? 0 : map.get("P001"));
        result.put("XSDJ", map.get("XSDJ") == null ? 0 : map.get("XSDJ"));
        result.put("XSXJ", map.get("XSXJ") == null ? 0 : map.get("XSXJ"));
        result.put("QUALITY", map.get("PZID"));
        result.put("DEPT_ID", map.get("MDID"));
        result.put("uniqueIdentify", map.get("uniqueIdentify"));

//        result.put("PRODUCT_UOM_ID", map.get("JLDWID") == null ? null : map.get("JLDWID"));
//
//        result.put("BUSINESS_CIRCLE_ID", map.get("SQID") == null ? null : map.get("SQID"));
//
//        result.put("PHONE_NUMBER", map.get("SJHM") == null ? null : map.get("SJHM"));
//        result.put("CAR_SERVICE_LEVEL_ID", map.get("CLFWDJID") == null ? null : map.get("CLFWDJID"));
//        result.put("CAR_LICENSE", map.get("CPHM") == null ? null : map.get("CPHM"));
//        result.put("COOPERATION_TYPE", map.get("HZLXID") == null ? null : map.get("HZLXID"));


//        result.put("XSZZID", map.get("XSZZID") == null ? null : map.get("XSZZID"));
//        result.put("MDLXID", map.get("MDLXID") == null ? null : map.get("MDLXID"));
//        result.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
        return result;
    }


    public Map getGS51Map(Map map) {
        map.put("DJGCID", "GS51");
        map.put("PLID", map.get("PLID"));
        map.put("PZID", map.get("PZID"));
        map.put("SPID", map.get("SPID"));
        map.put("GSID", map.get("GSID"));
        map.put("YYMS", map.get("YYMS"));
        map.put("KHID", map.get("KHID"));
        map.put("CGZZID", map.get("CGZZID"));
        map.put("JLDW", map.get("JLDW"));
        map.put("SYGSID", map.get("SYGSID"));
        map.put("JCGSID", map.get("JCGSID"));
        map.put("CLFWDJID", map.get("CLFWDJID"));
//        map.put("NOT_SPXJD_CREATE",1);
        return map;
    }

    public JSONObject getNewGS51Map(Map map) {
        JSONObject result = new JSONObject();
        result.put("conditionStrategyId", "GS51");
        result.put("uniqueIdentify", map.get("uniqueIdentify"));
        result.put("SYS_RQ", new Date());
//        Object spxjd = map.get("XJDH") == null ? "1" : map.get("XJDH");
//        result.put("NOT_SPXJD_CREATE", spxjd);
        if (map.get("GYSID") == null)result.put("SYS_NO_CHECK", "SUPPLIER_ID");


        result.put("CLASSIFY_ID", map.get("PLID"));
        result.put("QUALITY", map.get("PZID"));
        result.put("PRODUCT_ID", map.get("SPID"));
        result.put("COMPANY_ID", map.get("GSID"));
        result.put("OPERATION", map.get("NYYMS"));
        result.put("CUSTOMER_ID", map.get("KHID"));
        result.put("CAR_LICENSE", map.get("CPHM"));
        result.put("PUR_COMPANY_ID", map.get("CGZZID"));
        result.put("SUPPLIER_ID", map.get("GYSID"));
        result.put("BRAND_ID", map.get("PPID"));
//        result.put("JLDW", map.get("JLDW") == null ? null : map.get("JLDW"));
//        result.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
        result.put("JCGSID", map.get("JCGSID"));
        result.put("CAR_SERVICE_LEVEL_ID", map.get("CLFWDJID"));


        result.put("P001", map.get("P001"));
        result.put("XSDJ", map.get("XSDJ"));
        result.put("XSXJ", map.get("XSXJ"));
        result.put("XJDH", map.get("XJDH"));
        result.put("ACCESS_PROVIDER_ID", map.get("JRS"));
        result.put("PRODUCT_UOM_ID", map.get("JLDWID"));
        return result;
    }


    public JSONObject getGS51PriceItem(String obj){
        JSONObject re1 = JSONObject.parseObject(obj);
        if (re1.getString("S950") == null) {
            delPriceLogger(re1.getString("priceSource"));
            return new JSONObject(MapUtil.mapper(
                    "primaryPriceUnit", 0,
                    "retailPirce", 0,
                    "priceUnit", 0,
                    "pftPriceUnit", 0,
                    "managementFeeRate", 0,
                    "floorPrice", 0,  //最低限价
                    "clerkPriceLimit", 0,
                    "shopOwnerPriceLimit", 0,
                    "csoPriceLimit", 0,
                    "basePrice", 0,
                    "discountRate", 0,
                    "priceCostUnitInTax", 0,
                    "priceCostUnitExTax", 0,
                    "referTax", 0,
                    "modelPrice", 0,
                    "platformPriceCosInTax", 0,
                    "supplyChainManagement", 0,     //供应链管理费用
                    "supplyRate", 0
            ));
        }

        //
        return new JSONObject(MapUtil.mapper(
                "primaryPriceUnit", Arith.roundUp(re1.getDoubleValue("S950"), 2),
                "retailPirce", re1.getDoubleValue("F051"),
                "priceUnit", Arith.roundUp(re1.getDoubleValue("S950"), 2),
                "pftPriceUnit", Arith.roundUp(re1.getDoubleValue("S950"), 2),
                "managementFeeRate", 0,
                "floorPrice", re1.getDoubleValue("S950"),  //最低限价
                "clerkPriceLimit", re1.getDoubleValue("S950"),
                "shopOwnerPriceLimit", re1.getDoubleValue("S950"),
                "csoPriceLimit", re1.getDoubleValue("S950"),
                "basePrice", re1.getDoubleValue("S950"),
                "discountRate", re1.getDoubleValue("S950") / re1.getDoubleValue("S950"),
                "priceCostUnitInTax", re1.getDoubleValue("P009"),
                "priceCostUnitExTax", re1.getDoubleValue("P009"),
                "platformPriceCosInTax", re1.getDoubleValue("P001"),
                "referTax", re1.getDoubleValue("P008"),
                "modelPrice", re1.getDoubleValue("S006"),
                "supplyChainManagement", re1.getDoubleValue("P009"),     //供应链管理费用
                "supplyRate", re1.getDoubleValue("T001")
        ));
    }

    public Map getGS52Map(Map map) {
        map.put("DJGCID", "GS52");
        map.put("PLID", map.get("PLID") == null ? null : map.get("PLID"));
        map.put("PPID", map.get("PPID") == null ? null : map.get("PPID"));
        map.put("YYMS", map.get("YYMS") == null ? null : map.get("YYMS"));
        map.put("P001", map.get("P001") == null ? null : map.get("P001"));
        map.put("XSDJ", map.get("XSDJ") == null ? null : map.get("XSDJ"));
        map.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
        map.put("GSID", map.get("GSID") == null ? null : map.get("GSID"));
//        map.put("GYSID",map.get("GYSID") == null ?null : map.get("GYSID"));
        return map;
    }

    public JSONObject getNewGS52Map(Map map) {
        JSONObject result = new JSONObject();
        result.put("conditionStrategyId", "GS52");
        result.put("SYS_RQ", new Date());
        result.put("NOT_SPXJD_CREATE", "1");

        result.put("uniqueIdentify", map.get("uniqueIdentify") == null ? null : map.get("uniqueIdentify"));
        result.put("CLASSIFY_ID", map.get("PLID") == null ? null : map.get("PLID"));
        result.put("BRAND_ID", map.get("PPID") == null ? null : map.get("PPID"));
        result.put("OPERATION", map.get("NYYMS") == null ? null : map.get("NYYMS"));
        result.put("P001", map.get("P001") == null ? null : map.get("P001"));
        result.put("XSDJ", map.get("XSDJ") == null ? null : map.get("XSDJ"));
//        map.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
        result.put("COMPANY_ID", map.get("GSID") == null ? null : map.get("GSID"));
        result.put("PRODUCT_ID", map.get("SPID") == null ? null : map.get("SPID"));
//        map.put("GYSID",map.get("GYSID") == null ?null : map.get("GYSID"));
        return result;
    }

    public void getCG01Map(Map map) {
        map.put("DJGCID", "CG01");
        map.put("SPID", map.get("SPID") == null ? null : map.get("SPID"));
        map.put("GYSID", map.get("GYSID") == null ? null : map.get("GYSID"));
        map.put("JLDW", map.get("JLDW") == null ? null : map.get("JLDW"));
        map.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
    }

    public JSONObject getNewCG01Map(Map map) {
        JSONObject result = new JSONObject();
        result.put("conditionStrategyId", "CG01");
        result.put("SYS_RQ", new Date());
        result.put("NOT_SPXJD_CREATE", "1");

        result.put("PRODUCT_ID", map.get("SPID") == null ? null : map.get("SPID"));
        result.put("SUPPLIER_ID", map.get("GYSID") == null ? null : map.get("GYSID"));
//        result.put("JLDW", map.get("JLDW") == null ? null : map.get("JLDW"));
        result.put("CAR_LICENSE", map.get("CPHM") == null ? null : map.get("CPHM"));
        result.put("PRODUCT_UOM_ID", map.get("JLDWID") == null ? null : map.get("JLDWID"));

        result.put("COMPANY_ID", map.get("GSID") == null ? null : map.get("GSID"));

//        result.put("SYGSID", map.get("SYGSID") == null ? null : map.get("SYGSID"));
        return result;
    }


    /**
     * 转换定损来源字段
     * @param conditionModel
     * @return
     */
    public JSONObject getServerFiled(JSONObject conditionModel){
        if (conditionModel==null)throw new RuntimeException("conditionModel不能为空");
        Object fixedLossDept = conditionModel.get("fixedLossDept");
        if (fixedLossDept!=null){
            conditionModel.put("belongDept",conditionModel.get("fixedLossDept"));
        }
        return conditionModel;
    }
    /**
     * 查询商品信息
     * @param product
     * @return
     */
    public void checkProduct(Product product){
        if (product == null) throw new RuntimeException("该商品有误，未找到该商品");
        if ("5".equals(product.getState())) throw new RuntimeException("该商品状态为预上市不允许售卖！！详情请咨询采购。");
        if (product.getProductGroup() == null) throw new RuntimeException("该商品无商品组，请定义");
        if (product.getClassify() == null) throw new RuntimeException("该商品无商品分类，请定义");
        if (product.getBrand() == null) throw new RuntimeException("该商品无品牌，请定义");
        if (product.getUom() == null) throw new RuntimeException("该商品无计量单位，请定义");
        if (product.getCategory() == null) throw new RuntimeException("该商品无商品类目，请定义");
    }

    /**
     * 获取门店
     * @param filedName
     * @param conditionModel
     * @return
     */
    public Dept getDept(String filedName,JSONObject conditionModel){
        Dept dept = deptRepository.findOne(judgeString(filedName, "id", conditionModel));
        if (dept == null) throw new RuntimeException("该门店有误，未找到该门店");
        return dept;
    }
    /**
     * 查询商品信息
     *
     * @param condition
     * @return
     */
    public Product getProduct(JSONObject condition) {
        try {
            Product product = productRepository.findOne(judgeString("id", "", condition));
            if (product.getId() == null) throw new RuntimeException("商品信息有无，请检查");
            return product;
        } catch (Exception e) {
            throw new RuntimeException("商品信息有误，请检查" + (judgeString("id", "", condition)));
        }
    }

    /**
     * 根据传入参数解析编码
     *
     * @param param1
     * @param param2
     * @param condition
     * @return
     */
    public String judgeString(String param1, String param2, JSONObject condition) {
        try {
            if (param2.equals("")) {
                return condition.getString(param1);
            } else {
                return condition.getJSONObject(param1).getString(param2);
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取计量单位
     * @param product
     * @return
     */
    public ProductUom getProductUom(Product product) {
        ProductUom uom = new ProductUom();
        try {
            uom = productUomRepository.findAll(
                    JpaDsl.toCriteriaByEq("uomCategory.id", product.getUom().getUomCategory().getId(), "saleFirst", true)
            ).stream().findFirst().get();
        } catch (Exception e) {
            throw new RuntimeException("系统中不存在该商品默认销售计量单位:" + product.getUom().getName());
        }
        return uom;
    }
    /**
     * 获取车型服务等级
     * @param jeKunModelCode 配置车型编码
     * @return 车型服务等级
     */
    public String getCarModelServiceLevel(String jeKunModelCode){
        String carServiceLevel = "";
        if (!switched){
            if (!StringUtils.isEmpty(jeKunModelCode)) {
                JSONObject baseInfo = piManager.synErp(
                        "ipmServicePlanService.getCarDetailInfoForNew", MapUtil.mapper("PZCXID",jeKunModelCode));
                JSONObject carBase = JSONObject.parseObject(baseInfo.getString("obj"));
                if (!StringUtils.isEmpty(carBase.getString("CLFWDJMC"))){
                    carServiceLevel = carBase.getString("CLFWDJMC");
                }
            }
        }else {
            JSONObject carServiceLevelJson = SpringManager.getBean(FnApiService.class).getCarServiceLevel(jeKunModelCode);
            carServiceLevel= carServiceLevelJson.getString("CarServiceLevelName");
        }
        return carServiceLevel;
    }

    /**
     * 判断车型服务
     *
     * @param carJson
     * @param product
     */
    public void checkCarLimitType(JSONObject carJson, Product product, Dept dept) {
        if (carJson.getString("jekunModelCode") == null) throw new RuntimeException("车辆主数据缺失：配置车型");
        boolean a = SpringManager.getBean(CarConfigurationService.class).isStopService(carJson.getString("jekunModelCode"));

        if (a) {
            Area province;
            Classify classify;
            try {
                province = dept.getCompany().getParty().getCorporate().getOfficeProvince();
                if (province == null) throw new Exception("");
            } catch (Exception e) {
                throw new RuntimeException("门店对应公司的办公城市未定义，不允许做单");
            }

            try {
                classify = product.getClassify();
                if (classify == null) throw new Exception("");
            } catch (Exception e) {
                throw new RuntimeException("商品分类未定义，不允许做单");
            }
            boolean b = SpringManager.getBean(CarTypeLimitService.class).isCarTypeLimit(province, classify);

            if (!b)
                throw new RuntimeException("该车型停止服务，不允许做该分类下的项目，分类名称：" + classify.getName() + "【此车型已停止服务,请走钉钉审批‘开放车型服务申请’】");
        }
    }

}
